using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace UNGDUNG
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        #region Common Variable
        clsDatabases cls;
        DataTable dt;
        ListViewItem item1;
        Form frm;
        string selectedNode = "";
        string parentNode = "";
        #endregion
        #region Resize
        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            tvDatabases.Width = splitContainer1.Panel1.Width;
            lvObjects.Width = splitContainer1.Panel2.Width;
            lbHeader.Width = splitContainer1.Panel2.Width;
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            tvDatabases.Height = Height-100;
            lvObjects.Height = Height-100;
            lbHeader.Width = splitContainer1.Panel2.Width  ;
        }
        #endregion
        private void frmMain_Load(object sender, EventArgs e)
        {
            
            LeftMenu();
            lbUser.Text = "UserName: " + SystemInformation.UserName;
        }
        #region LeftMenu
        void LeftMenu()
        {    
            CreateParentNode(tvDatabases.Nodes, "A", "Console Root", 0, 1);
            CreateParentNode(tvDatabases.Nodes[0].Nodes, "B", "Microsoft SQL Server", 2, 3);
            CreateParentNode(tvDatabases.Nodes[0].Nodes[0].Nodes , "C", "Microsoft SQL Server", 4, 5);
            CreateParentNode(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes, "0", SystemInformation.ComputerName+ "(Windows NT)", 6, 6);
            cls = new clsDatabases("");
            SQLServers(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes);
            Databases(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes["Databases"].Nodes);
            Security(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes["Security"].Nodes );            
        }
        void SQLServers(TreeNodeCollection tn)
        {
            foreach(string str in clsStatic.SQLServer)
            {
                tn.Add(str, str, 0, 1);
            }
        }
        void Security(TreeNodeCollection tn)
        {
            foreach (string str in clsStatic.SQLSecurity)
            {
                tn.Add(str, str, 0, 1);
            }
        }
        void Databases(TreeNodeCollection tn)
        {
            tn.Clear();       
            dt = cls.GetTable("Databases");
            if (dt != null)
            {
                foreach (DataRow r in dt.Rows)
                {
                    tn.Add(Convert.ToString(r[0]), Convert.ToString(r[0]), 2,2);
                    DatabaseObjects(tn[Convert.ToString(r[0])].Nodes );
                }
            }
        }
        void DatabaseObjects(TreeNodeCollection tn)
        {
            
            for (int i = 0; i <clsStatic.DatabaseObjects.GetLength(0);i++ )
            {
                tn.Add(clsStatic.DatabaseObjects[i,0], clsStatic.DatabaseObjects[i,1], i+10, i+10);
            }
        }
        #endregion
        #region Create Nodes
        void CreateParentNode(TreeNodeCollection tn, string strkey, string strname, int iImage, int iSelectImage)
        {
            tn.Add(strkey, strname, iImage, iSelectImage);
        }   
        #endregion
        #region View Objects
        void ViewObjects(ListView lv, string key,string[] header,int[] columnwidth, int image)
        {
            
            
            dt = cls.GetTable(key);
            for(int i=0;i<header.Length;i++)
            {
                lv.Columns.Add(header[i], columnwidth[i]);
            }             
            if (dt != null)
            {
                foreach (DataRow r in dt.Rows)
                {
                    item1 = new ListViewItem(Convert.ToString(r[0]), image);
                    object[] o = r.ItemArray;
                    for(int j=1;j<o.Length;j++)
                    {
                        item1.SubItems.Add(Convert.ToString(o[j]));                        
                    }
                    lv.Items.Add(item1);
                }
            }
            dt = null;
        }
        void ViewObjects(ListView lv, string key,string parent, string type, string[] header, int[] columnwidth, int image)
        {
            
            
            dt = cls.GetTable(key, parent, type);
            for (int i = 0; i < header.Length; i++)
            {
                lv.Columns.Add(header[i], columnwidth[i]);
            }
            if (dt != null)
            {
                foreach (DataRow r in dt.Rows)
                {
                    item1 = new ListViewItem(Convert.ToString(r[0]), image);
                    object[] o = r.ItemArray;
                    for (int j = 1; j < o.Length; j++)
                    {
                        item1.SubItems.Add(Convert.ToString(o[j]));
                    }
                    lv.Items.Add(item1);
                }
            }
            dt = null;
        }
        void ViewObjects(ListView lv, string key, string[] header, string[] value, int[] columnwidth, int image)
        {
            
                     
            for (int i = 0; i < header.Length; i++)
            {
                lv.Columns.Add(header[i], columnwidth[i]);
            }            
            if (dt != null)
            {                
                for(int j=1; j<value.Length;j++)
                {

                    lv.Items.Add(Convert.ToString(value[j]), image); 
                }
                
            }
           
        }
        #endregion        
        #region Event
        private void tvDatabases_AfterSelect(object sender, TreeViewEventArgs e)
        {
            lvObjects.View = View.Details;
            lvObjects.Items.Clear();  
            parentNode = "";
            if(e.Node.Parent!=null)
                parentNode = e.Node.Parent.Text;
            selectedNode = e.Node.Text;
            ShowObjects(selectedNode, parentNode);
            ShowMenu(selectedNode);
        }
        #endregion
        #region Menu
        void ShowMenu(string key)
        {
            switch (key)
            {
                case "Databases":
                    ActionBackup.Enabled = true;
                    ActionNew.Text = "New Database";
                    ActionDelete.Text = "Delete Database";
                    ActionBackup.Text = "Backup Database";
                    break;
                case "Logins":
                    ActionNew.Text = "New Login";
                    ActionDelete.Text = "Delete Login";
                    ActionBackup.Enabled = false; ;
                    break;
                case "Server Roles":
                    ActionNew.Text = "New Server Role";
                    ActionDelete.Text = "Delete Server Role";
                    ActionBackup.Enabled = false; 
                    break;
                case "Diagrams":
                    ActionNew.Text = "New Diagram";
                    ActionDelete.Text = "Delete Diagram";
                    ActionBackup.Enabled = false;
                    break;
                case "Tables":
                    ActionNew.Text = "New Table";
                    ActionDelete.Text = "Delete Table";
                    ActionBackup.Enabled = false; 
                    break;
                case "Views":
                    ActionNew.Text = "New View";
                    ActionDelete.Text = "Delete View";
                    ActionBackup.Enabled = false; 
                    break;
                case "Stored Procedure":
                    ActionNew.Text = "New Procedure";
                    ActionDelete.Text = "Delete Procedure";
                    ActionBackup.Enabled = false; 
                    break;
                case "Users":
                    ActionNew.Text = "New User";
                    ActionDelete.Text = "Delete User";
                    ActionBackup.Enabled = false; 
                    break;
                case "Roles":
                    ActionNew.Text = "New Role";
                    ActionDelete.Text = "Delete Role";
                    ActionBackup.Enabled = false; 
                    break;
                case "Defaults":
                    ActionNew.Text = "New Default";
                    ActionDelete.Text = "Delete Default";
                    ActionBackup.Enabled = false;
                    break;
                case "Rules":
                    ActionNew.Text = "New Rule";
                    ActionDelete.Text = "Delete Rule";
                    ActionBackup.Enabled = false;
                    break;
                case "Functions":
                    ActionNew.Text = "New Function";
                    ActionDelete.Text = "Delete Function";
                    ActionBackup.Enabled = false;
                    break;
            }
        }
        #endregion
        #region Show Objects
        void ShowObjects(string key,string parentkey)
        {
            lvObjects.Clear();
            string[] header = null;int[] columnwidth=null;;
            switch(key)
            {
                case "Databases":
                    header = new string[] { "Name",  "Create Date", "File Name"};
                    columnwidth = new int[] { 200, 150, 300 };
                    break;
                case "Logins":
                    header =new string[]{"Name", "Type", "Create Date", "Database", "Language" };
                    columnwidth =new int[]{ 200, 150, 100, 100, 150 };                   
                    break;
                case "Server Roles":
                    header =new string[]{ "Full Name","Name"};                    
                    columnwidth = new int[] { 200,200};
                    break;
                case "Tables":
                case "Views":
                case "Stored Procedure":
                    header = new string[] { "Name", "Owner","Type","Create Date" };
                    columnwidth = new int[] { 200, 150,150,150 };
                    break;
                case "Users":
                    header = new string[] { "Name", "Full Name",  "Create Date" };
                    columnwidth = new int[] { 200, 150, 150  };
                    break;
                case "Roles":
                    header = new string[] { "Name", "Type"};
                    columnwidth = new int[] { 200, 150  };
                    break;
            }
            switch (key)
            {
                case "Databases":
                    ViewObjects(lvObjects, key, "master","",header, columnwidth, 3);
                    break;
                case "Logins":
                    ViewObjects(lvObjects, key, header, columnwidth,7);
                    break;
                case "Server Roles":
                    ViewObjects(lvObjects, key, header,columnwidth,8);
                    break;
                case "Tables":
                    ViewObjects(lvObjects, key, parentkey, "U",header, columnwidth, 12);
                    break;
                case "Views":
                    ViewObjects(lvObjects, key, parentkey, "V", header, columnwidth, 13);
                    break;
                case "Stored Procedure":
                    ViewObjects(lvObjects, key, parentkey, "P", header, columnwidth, 14);
                    break;
                case "Users":
                    ViewObjects(lvObjects, key, parentkey, "", header, columnwidth, 15);
                    break;
                case "Roles":
                    ViewObjects(lvObjects, key, parentkey, "", header, columnwidth, 16);
                    break;
            }
        }
        #endregion
        #region Type of View Objects
        private void detailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lvObjects.View = View.Details;
        }

        private void smallImagesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lvObjects.View = View.SmallIcon;
        }
        #endregion
        #region Right Shortcut
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (!selectedNode.Equals("") && !parentNode.Equals(""))
            {
                string name = "";
                

                frm = new frmInput();
                frm.Text = "New Name of " + selectedNode.Substring(0,selectedNode.Length-1);
                frm.ShowDialog(this);
                name = clsStatic.strInput;                              
                if(selectedNode.Equals("Databases") || parentNode.Equals("Databases"))
                {
                        if (cls.ExecuteObject(selectedNode, "create database ", name))
                        {
                            ShowObjects(selectedNode, parentNode);
                            Databases(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes["Databases"].Nodes);
                        }
                }
                if (selectedNode.Equals("Logins") || parentNode.Equals("Logins"))
                {                  
                        if (cls.ExecuteObject(selectedNode, "sp_addlogin ", name))
                        {
                            ShowObjects(selectedNode, parentNode);                            
                        }
                      
                }
            }
        } 
       

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (!selectedNode.Equals(""))
            {
                ListViewItem liv = lvObjects.FocusedItem;
                string name = liv.SubItems[0].Text;
                if (MessageBox.Show("Are you sure to drop '" + 
                    name + "'", "C# 2005", 
                    MessageBoxButtons.YesNo, 
                    MessageBoxIcon.Warning) == 
                    DialogResult.Yes)
                {
                    switch (selectedNode)
                    {
                        case "Databases":
                            if (cls.DropObject(selectedNode, 
                                "drop database ", name))
                            {
                                ShowObjects(selectedNode, parentNode);
                                Databases(tvDatabases.Nodes[0].
                                    Nodes[0].Nodes[0].Nodes[0].
                                    Nodes["Databases"].Nodes);
                            }
                            break;
                        case "Tables":
                            if (cls.DropObject(selectedNode,
                                "drop table ", parentNode +
                                ".dbo.[" + name + "]"))
                            {
                                ShowObjects("Tables", parentNode);
                            }
                            break;
                        case "Views":
                            if (cls.DropObject(selectedNode,
                                "drop view ", parentNode +
                                ".dbo.[" + name + "]"))
                            {
                                ShowObjects("Views", parentNode);
                            }
                            break;
                        case "Stored Procedures":
                            if (cls.DropObject(selectedNode, 
                                "drop proc ", parentNode + 
                                ".dbo.[" + name + "]"))
                            {
                                ShowObjects("Stored Procedures", parentNode);
                            }
                            break;
                        case "Logins":
                            if (cls.DropObject(selectedNode, 
                                "sp_droplogin ", name))
                            {
                                ShowObjects("Logins", parentNode);
                            }
                            break;
                    }
                }
            }
        }
        #endregion
        #region Left Shortcut
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            if (!selectedNode.Equals(""))
            {
                if (MessageBox.Show("Are you sure to drop '" + selectedNode + "'", "C# 2005", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    switch (parentNode)
                    {
                        case "Databases":
                            if (cls.ExecuteObject(parentNode, "drop ", selectedNode))
                            {
                                ShowObjects(parentNode, parentNode);
                                Databases(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes["Databases"].Nodes);
                            }
                            break;
                        case "Tables":
                            if (cls.ExecuteObject(parentNode, "drop ", "["+selectedNode+"]"))
                            {
                                ShowObjects("Tables", parentNode);
                                
                            }
                            break;
                    }
                }
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {

            if (!parentNode.Equals("") && !selectedNode.Equals(""))
            {
                 
                string name = "";               

                frm = new frmInput();
                frm.Text = "New Name of " + selectedNode.Substring(0,selectedNode.Length - 1);
                frm.ShowDialog(this);
                name = clsStatic.strInput;
                if (selectedNode.Equals("Databases") || parentNode.Equals("Databases"))
                {
                    if (cls.ExecuteObject(selectedNode, "create database ", name))
                    {
                        ShowObjects(selectedNode, parentNode);
                        Databases(tvDatabases.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Nodes["Databases"].Nodes);
                    }
                }
                if (selectedNode.Equals("Logins") || parentNode.Equals("Logins"))
                {
                    if (cls.ExecuteObject(selectedNode, "sp_addlogin ", name))
                    {
                        ShowObjects(selectedNode, parentNode);
                    }

                }
            }
        }
        #endregion

        private void ActionNew_Click(object sender, EventArgs e)
        {

        }

        private void lvObjects_DoubleClick(object sender, EventArgs e)
        {
            frm = null;
            //MessageBox.Show(parentNode + " - " + selectedNode );
            ListViewItem liv = lvObjects.FocusedItem;
            string name = liv.SubItems[0].Text;
            lbHeader.Text = name;
            clsStatic.strMasterInput = parentNode;
            clsStatic.strInput = name;
            switch (selectedNode)
            {
                case "Databases":
                    frm= new frmDatabase();
                    frm.Text = "Property of Database - " + name;                    
                    break;
                case "Tables":
                    frm = new frmTable();
                    frm.Text = "Property of Table - " + name;
                    break;
                case "Views":
                    frm = new frmView();
                    frm.Text = "Property of View - " + name;
                    break;
                case "Stored Procedure":
                    frm = new frmStoredProcedure();
                    frm.Text = "Property of Stored Procedure - " + name;
                    break;
                case "Logins":
                    frm = new frmLogin();
                    frm.Text = "Property of Login - " + name;
                    break;
            }
            if(frm!=null)
                frm.ShowDialog();
        }

        private void ActionBackup_Click(object sender, EventArgs e)
        {            
            if (parentNode.Equals("Databases"))
            {
                frm =new  frmBackup(selectedNode);
                frm.Text = "Backup database - " + selectedNode;
                frm.ShowDialog();
            }
            
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (parentNode.Equals("Databases"))
            {
                frm = new frmBackup(selectedNode);
                frm.Text = "Backup database - " + selectedNode;
                frm.ShowDialog();
            }
        }

        private void aboutUsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frm = new frmAboutUs();
            frm.ShowDialog();
        }

        private void lvObjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem liv = lvObjects.FocusedItem;
            string name = liv.SubItems[0].Text;
            lbHeader.Text = name;
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            MessageBox.Show (e.ClickedItem.ToolTipText);
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Are you sure to exit?","HUUKHANG.COM",MessageBoxButtons.OKCancel,MessageBoxIcon.Question)==DialogResult.OK)
                Application.Exit();
        }

        private void minimizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Maximized;
                minimizeToolStripMenuItem.Text = "Minimized";
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
                minimizeToolStripMenuItem.Text = "Maximized";
            }
        }

        private void queryAnanlyzerToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void ActionDelete_Click(object sender, EventArgs e)
        {

        }

        private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        

    

        
    }
}